package com.walle.concurrenttest.pattern.readwritelock;

import java.util.Arrays;

/**
 * @author zhangjiapeng
 * @Package com.walle.concurrenttest.pattern.readwritelock
 * @Description: ${todo}
 * @date 2019/2/20 13:50
 */
public class Data {

    private final char[] buffer;
    private final ReadWriteLock readWriteLock = new ReadWriteLock();

    public Data(int size) {
        this.buffer = new char[size];
        for (int i = 0; i < buffer.length; i++) {
            buffer[i] = '*';
        }
    }

    public char[] read() throws InterruptedException {
        readWriteLock.readLock();
        try {
            return doRead();
        } finally {
            readWriteLock.readUnLock();
        }
    }

    private char[] doRead(){
        char[] newBuf = new char[buffer.length];
        System.arraycopy(buffer,0,newBuf,0,buffer.length);
        slowly();
        return newBuf;
    }

    public void write(char c) throws InterruptedException {
        readWriteLock.writeLock();
        try {
            doWrite(c);
        } finally {
            readWriteLock.writeUnLock();
        }
    }
    private void doWrite(char c){
        for (int i = 0; i < buffer.length; i++) {
            buffer[i] = c;
            slowly();
        }
    }

    private void slowly(){
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }



}
